/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.app.model.AppCaseBeforeDocumentTemporaryRecord;
import com.icinfo.cloud.provider.punish.dto.AppDocumentCommonSaveDto;
import com.icinfo.cloud.provider.punish.dto.AppDocumentTemporaryRecordSaveDto;
import com.icinfo.cloud.provider.punish.dto.ZtcCurrentUserTemporaryInfoDto;
import com.icinfo.cloud.provider.punish.enums.ZtcSourceTypeEnum;
import com.icinfo.cloud.provider.punish.mapper.AppCaseBeforeDocumentTemporaryRecordMapper;
import com.icinfo.cloud.provider.punish.service.IAppCaseBeforeDocumentTemporaryRecordService;
import com.icinfo.cloud.provider.punish.vo.AppDocumentCurrentUserTemporaryVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Optional;

/**
 * 办案直通车文书暂存服务层
 *
 * @author Junfeng.Chen
 * @date 2024/1/10 11:26
 **/
@Slf4j
@Service
@Transactional(rollbackFor = {Error.class, Exception.class})
public class AppCaseBeforeDocumentTemporaryRecordServiceImpl extends MyBatisServiceSupport implements IAppCaseBeforeDocumentTemporaryRecordService {
    @Resource
    private AppCaseBeforeDocumentTemporaryRecordMapper appCaseBeforeDocumentTemporaryRecordMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(AppDocumentTemporaryRecordSaveDto dto) {
        //保存校验
        saveValidation(dto);
        //清空暂存
        removeCurrentUserTemporaryRecord(dto.getDocumentCatalogCode(), dto.getSourceType(), dto.getSourceId());
        //组装暂存数据
        AppCaseBeforeDocumentTemporaryRecord temporaryRecord = assemblyTemporaryRecord(dto);
        //插入
        appCaseBeforeDocumentTemporaryRecordMapper.insert(temporaryRecord);
    }

    /**
     * 组装暂存实体模型
     */
    private AppCaseBeforeDocumentTemporaryRecord assemblyTemporaryRecord(AppDocumentTemporaryRecordSaveDto dto) {
        UserDTO userDTO = getUser();
        AppCaseBeforeDocumentTemporaryRecord temporaryRecord = new AppCaseBeforeDocumentTemporaryRecord();
        temporaryRecord.setId(StringUtils.uuid());
        temporaryRecord.setDocumentCatalogCode(dto.getDocumentCatalogCode());
        temporaryRecord.setContent(JSON.toJSONString(dto.getContent()));
        temporaryRecord.setAddUser(String.valueOf(userDTO.getUserId()));
        temporaryRecord.setOrgCode(userDTO.getOrgCode());
        temporaryRecord.setAreaCode(userDTO.getAreaCode());
        temporaryRecord.setCreateTime(LocalDateTime.now());
        //处理sourceType为空的情况，设置来源信息
        ZtcSourceTypeEnum ztcSourceTypeEnum = Optional.ofNullable(dto.getSourceType()).orElse(ZtcSourceTypeEnum.CF_ZTC);
        settingSource(dto.getSourceId(), ztcSourceTypeEnum, temporaryRecord);
        return temporaryRecord;
    }

    /**
     * 设置来源信息
     */
    private void settingSource(String sourceId, ZtcSourceTypeEnum sourceTypeEnum, AppCaseBeforeDocumentTemporaryRecord temporaryRecord) {
        if (ZtcSourceTypeEnum.CF_ZTC.equals(sourceTypeEnum)) {
            //处罚直通车来源，无来源id 默认为0
            temporaryRecord.setSourceType(ZtcSourceTypeEnum.CF_ZTC.getCode());
            temporaryRecord.setSourceId(Constant.STRING_0);
            return;
        }
        Assert.notBlank(sourceId, "检查对象id不能为空");
        temporaryRecord.setSourceId(sourceId);
        temporaryRecord.setSourceType(sourceTypeEnum.getCode());
    }

    /**
     * 保存校验
     *
     * @param dto
     */
    private static void saveValidation(AppDocumentTemporaryRecordSaveDto dto) {
        AppDocumentCommonSaveDto content = dto.getContent();
        if (Constant.STRING_2.equals(content.getOperateType())) {
            throw new BusinessException("重置文书不允许暂存");
        }
    }

    @Override
    public AppDocumentCurrentUserTemporaryVo getCurrentUserTemporaryInfo(ZtcCurrentUserTemporaryInfoDto dto) {
        AppDocumentCurrentUserTemporaryVo vo = new AppDocumentCurrentUserTemporaryVo();
        vo.setHasTemporary(false);
        AppCaseBeforeDocumentTemporaryRecord temporaryRecord = getCurrentUserTemporaryRecord(dto);
        if (Objects.isNull(temporaryRecord)) {
            return vo;
        }
        vo.setHasTemporary(true);
        vo.setContent(JSON.parseObject(temporaryRecord.getContent(), AppDocumentCommonSaveDto.class));
        return vo;
    }

    @Override
    public void removeCurrentUserTemporaryRecord(String documentCatalogCode, ZtcSourceTypeEnum sourceType, String sourceId) {
        UserDTO userDTO = getUser();
        AppCaseBeforeDocumentTemporaryRecord temporaryRecord = new AppCaseBeforeDocumentTemporaryRecord();
        temporaryRecord.setAddUser(String.valueOf(userDTO.getUserId()));
        temporaryRecord.setOrgCode(userDTO.getOrgCode());
        temporaryRecord.setAreaCode(userDTO.getAreaCode());
        temporaryRecord.setDocumentCatalogCode(documentCatalogCode);
        //设置来源信息
        ZtcSourceTypeEnum ztcSourceTypeEnum = Optional.ofNullable(sourceType).orElse(ZtcSourceTypeEnum.CF_ZTC);
        settingSource(sourceId, ztcSourceTypeEnum, temporaryRecord);
        appCaseBeforeDocumentTemporaryRecordMapper.delete(temporaryRecord);
    }

    /**
     * 获取当前用户直通车暂存记录
     *
     * @return 查询到的暂存记录，可能为空
     */
    private AppCaseBeforeDocumentTemporaryRecord getCurrentUserTemporaryRecord(ZtcCurrentUserTemporaryInfoDto dto) {
        UserDTO userDTO = getUser();
        AppCaseBeforeDocumentTemporaryRecord temporaryRecord = new AppCaseBeforeDocumentTemporaryRecord();
        temporaryRecord.setAddUser(String.valueOf(userDTO.getUserId()));
        temporaryRecord.setOrgCode(userDTO.getOrgCode());
        temporaryRecord.setAreaCode(userDTO.getAreaCode());
        temporaryRecord.setDocumentCatalogCode(dto.getDocumentCatalogCode());
        // 设置来源信息
        ZtcSourceTypeEnum ztcSourceTypeEnum = Optional.ofNullable(dto.getSourceType()).orElse(ZtcSourceTypeEnum.CF_ZTC);
        settingSource(dto.getSourceId(), ztcSourceTypeEnum, temporaryRecord);
        return appCaseBeforeDocumentTemporaryRecordMapper.selectOne(temporaryRecord);
    }
}
